#-*- coding: utf-8 -*-
import traceback, sys, cStringIO
import datetime, time, cgi
import pytz
from django.conf import settings

def get_utc_time(dt = None):
    if dt is None:
        dt = datetime.datetime.utcnow()
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo = pytz.utc)
    
    if dt.tzname()!='UTC':
        dt = dt.astimezone(pytz.utc)
    return dt

def get_local_time(dt = None):
    utc_dt = get_utc_time(dt)
    l_u_dt = utc_dt.astimezone(pytz.timezone(settings.TIME_ZONE))

    return l_u_dt

def date_str(dt = None):
    if dt is None:
        dt = datetime.datetime.utcnow()
    if isinstance(dt, datetime.datetime):
        dt = get_local_time(dt)

    return dt.strftime('%Y-%m-%d')

def time_str(dt = None):
    dt = get_local_time(dt)

    return dt.strftime('%Y-%m-%d %H:%M:%S %z')

def rfc3339_time_str(dt = None):
    dt = get_utc_time(dt)
    return dt.strftime('%Y-%m-%dT%H:%M:%SZ')

def only_time_str(dt = None):
    dt = get_local_time(dt)

    return dt.strftime('%H:%M:%S')

def get_time(dt = None):
    utc_dt = get_utc_time(dt)
    
    t = (utc_dt - datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc))
    t = float(t.days*86400+t.seconds+t.microseconds/1000000.0)

    return t

def parse_date(d):
    return datetime.date(*map(int, d.split('-')))

def parse_time(d):
    t = time.strptime(d, '%Y-%m-%d %H:%M:%S')
    dt = datetime.datetime(*(t[0:6]), **({'tzinfo':get_local_time().tzinfo}))
    dt = get_utc_time(dt)

    return dt

def human_time(target_time):
  now = datetime.datetime.utcnow()
  tdelta = now - target_time

  if tdelta.days < 0:
    ret_time = u"就在刚才"
  else:
    if tdelta.days > 0:
      ret_time = u"%d天前" % tdelta.days
    elif (tdelta.seconds / (60*60)) > 0:
      ret_time = u"%d小时前" % (tdelta.seconds / (60*60))
    elif (tdelta.seconds / (60)) > 0:
      ret_time = u"%d分钟前" % (tdelta.seconds / 60)
    else:
      ret_time = u"就在刚才"

  return ret_time
